<template>
  <div class="page-container">
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" />

    <table-index :table="table" @loadData="loadData">
      <!-- 支出单号 -->
      <template #code="{ record }">
        <div class="order-info-item">
          <div>{{ record.code }}</div>
        </div>
        <!-- 订单标签 -->
        <a-space wrap>
          <tag type="primary" v-for="(item, index) in record.labelList" :key="index">{{ item }}</tag>
        </a-space>
      </template>
      <!-- 审批状态 -->
      <template #checkStatus="{ record }">
        <div :class="['checkStatus_' + record.checkStatus]">{{ record.checkStatusName }}</div>
        <!-- 驳回 -->
        <a-tag style="cursor: pointer" bordered color="blue" v-if="record.checkStatus == 6" @click="showReason(record)">原因</a-tag>
      </template>
      <!-- 审批流 -->
      <template #checkFlowList="{ record }">
        <!-- 无需审批显示- -->
        <div v-if="record.checkStatus == 1">-</div>
        <template v-else>
          <div v-for="(item, index) in record.checkFlowList" :key="index">
            <div v-if="item.staffId">
              <div class="item-content">
                <span class="fixed_width">
                  {{ item.staffName ? (item.staffName.length > 3 ? item.staffName.substr(0, 3) + '...' : item.staffName) : '-' }}
                </span>
                <a-tag
                  :color="getTagColor(item.statusName)"
                  style="margin-left: 4px"
                  v-if="item.statusName == '同意' || item.statusName == '已驳回' || item.statusName == '待审批'"
                >
                  {{ item.statusName }}
                </a-tag>
                <span :class="['checkStatus_' + item.status]" v-else>{{ item.statusName || '-' }}</span>
              </div>
              <div class="td-divider" v-if="index != record.checkFlowList.filter((i) => i.staffId).length - 1"></div>
            </div>
          </div>
        </template>
      </template>
      <!-- 关联业务信息 -->
      <template #orderInfo="{ record }">
        <div v-if="record.workCode">
          <div class="order-info-item">
            {{ record.workTypeName }}
          </div>
          <div class="order-info-item link" @click="toWorkDetail(record)">
            {{ record.workCode }}
          </div>
        </div>
        <div class="td-divider" v-if="record.workCode && record.businessCode"></div>
        <div v-if="record.businessCode">
          <div class="order-info-item">
            {{ record.businessTypeName }}
          </div>
          <div class="order-info-item link" @click="toOrderDetail(record)">
            {{ record.businessCode }}
          </div>
        </div>
      </template>
      <!-- 付款状态 -->
      <template #payStatusName="{ record }">
        <span :class="['payStatus_' + record.payStatus]">{{ record.payStatusName || '-' }}</span>
      </template>
      <!-- 支出费项 -->
      <template #feeList="{ record }">
        <template v-for="(item, index) in record.feeList" :key="index">
          {{ item.itemName }}
          <div class="td-divider" v-if="index != record.feeList.length - 1"></div>
        </template>
      </template>
      <!-- 费用金额 -->
      <template #feeAmount="{ record }">
        <div v-for="(item, index) in record.feeList" :key="index">
          <span> {{ item.amount }} </span>
          <div class="td-divider" v-if="index != record.feeList.length - 1"></div>
        </div>
      </template>
    </table-index>

    <!-- 原因弹框 -->
    <ReasonModal ref="reasonModalRef" />
  </div>
</template>

<script setup name="OperateCostBill">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import { useExport } from '@/hooks/list'
  import { usePageDict } from '@/hooks/useDict'
  import { getCostBillApi, exportExcelCostBillApi } from '@/api/business/operateCost'
  import useNavigate from '@/hooks/useNavigate'
  import ReasonModal from '@/views/business/operate-cost/components/reason-modal.vue'
  import { usePermission } from '@/hooks/usePermission'

  const { navigateTo } = useNavigate()
  const dict = usePageDict('getCostEnums')

  // dateTime Attrs
  const dateTimeAttrs = {
    type: 'i-range-picker',
    attrs: {
      showTime: true,
      timePickerProps: {
        defaultValue: ['00:00:00', '23:59:59'],
      },
    },
  }

  // 查询条件
  const searchList = computed(() => {
    return [
      { label: '支出单号', prop: 'code', placeholder: '请输入', type: 'a-input' },
      { label: '支出单类型', prop: 'costType', type: 'a-select', options: dict.costTypeEnum },
      { label: '工单号', prop: 'workCode', placeholder: '请输入', type: 'a-input' },
      { label: '工单类型', prop: 'workType', type: 'a-select', options: dict.workTypeEnum },
      { label: '业务单号', prop: 'businessCode', placeholder: '请输入', type: 'a-input' },
      { label: '业务类型', prop: 'businessType', type: 'a-select', options: dict.businessTypeEnum },
      { label: '标签', prop: 'labelList', type: 'a-select', options: dict.labelEnum, multiple: true },
      { label: '审批状态', prop: 'checkStatusList', type: 'a-select', options: dict.checkStatusEnum, multiple: true },
      { label: '审批人', prop: 'checkStaffId', type: 'remote-select', attrs: { type: 'operate_staff_list' } },
      { label: '付款状态', prop: 'payStatus', type: 'a-select', options: dict.payStatusEnum },
      { label: '费用产生机构', prop: 'feeOrgId', type: 'remote-select', attrs: { type: 'org_listByStaff' } },
      { label: '支出费项', prop: 'feeItem', type: 'sysdict-select', attrs: { code: 'cost_fee_item', addable: false } },
      { label: '申请人', prop: 'applyStaffId', type: 'remote-select', attrs: { type: 'operate_staff_list' } },
      {
        label: '申请时间',
        prop: 'applyTimeArr',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.applyTimeStart = value[0]
          queryParam.applyTimeEnd = value[1]
        },
      },
      {
        label: '付款时间',
        prop: 'payTimeArr',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.payTimeStart = value[0]
          queryParam.payTimeEnd = value[1]
        },
      },
    ]
  })

  // 定义 queryParam
  const queryParam = reactive({
    // 申请时间
    applyTimeArr: [],
    // 付款时间
    payTimeArr: [],
  })

  // table 配置
  const table = useTable({
    columns: [
      { title: '支出单号', slotName: 'code', width: 180, fixed: 'left' },
      { title: '审批状态', slotName: 'checkStatus', width: 100 },
      { title: '审批流', slotName: 'checkFlowList', width: 140 },
      { title: '支出单类型', dataIndex: 'costTypeName', width: 110 },
      { title: '关联业务信息', slotName: 'orderInfo', width: 240 },
      { title: '费用产生机构', dataIndex: 'feeOrgName', ellipsis: true },
      { title: '付款状态', slotName: 'payStatusName', width: 100 },
      { title: '支出总额', dataIndex: 'amount', unit: '元', width: 120 },
      { title: '支出费项', slotName: 'feeList', width: 120 },
      { title: '费用金额', slotName: 'feeAmount', unit: '元', width: 120 },
      { title: '申请人', dataIndex: 'applyStaffName', width: 120 },
      { title: '申请时间', dataIndex: 'applyTime', width: 170 },
      { title: '付款时间', dataIndex: 'payTime', width: 170 },
      { title: '申请备注', dataIndex: 'remark', ellipsis: true },
    ],
    tableLoading: false,
    operates: [
      {
        label: '详情',
        permission: 'svms:finance:bill:operate-cost.detail',
        method: (record) => {
          navigateTo(`/operate-cost/detail/${record.id}`)
        },
      },
    ],
    buttons: [
      {
        label: '导出',
        permission: 'svms:finance:bill:operate-cost.export',
        method: () => {
          useExport(exportExcelCostBillApi, queryParam)
        },
      },
    ],
  })
  // 列表接口调用
  const loadData = (page) => {
    const fn = useFetchTableDataApi(table, queryParam, getCostBillApi)
    fn(page).then((res) => {
      // 过滤掉审批流程没有审批人的
      res.data.forEach((item) => {
        item.checkFlowList = item.checkFlowList.filter((item) => item.staffId)
      })
    })
  }

  // 跳转工单详情
  const toWorkDetail = (val) => {
    if (usePermission('svms:business:workOrder:work.details')) {
      navigateTo(
        `/work-order/detail/${val.workId}?tab=1&orderId=${val.businessId}&workCode=${val.workCode}&orderType=${val.businessType}`,
        `${val.workCode}-工单详情`
      )
    }
  }
  // 跳转业务单详情
  const toOrderDetail = (val) => {
    if (val.businessType == '1') {
      if (usePermission('svms:order:short-order.detail')) {
        navigateTo(`/short-order/detail/${val.businessId}`, `${val.businessCode}-短租详情`)
      }
    } else {
      if (usePermission('svms:order:long-order.detail')) {
        navigateTo(`/long-order/detail/${val.businessId}`, `${val.businessCode}-长租详情`)
      }
    }
  }

  // 展示原因弹框
  const reasonModalRef = ref()
  const showReason = (record) => {
    reasonModalRef.value.open(record, 'bill')
  }

  // 根据标签内容返回不同的颜色值
  const getTagColor = (label) => {
    const tagColors = {
      同意: 'green',
      待审批: 'orange',
      已驳回: 'red',
    }
    return tagColors[label] || ''
  }

  onMounted(() => {
    loadData()
  })
</script>

<style lang="less" scoped>
  .checkStatus {
    &_1 {
      color: #722ed1;
    }
    &_2 {
      color: #ff7d00;
    }
    &_3 {
      color: #1890ff;
    }
    &_4 {
      color: #00b42a;
    }
    &_5 {
      color: #86909c;
    }
    &_6 {
      color: #f76964;
    }
    &_7 {
      color: #f76964;
    }
  }
  .payStatus_ {
    &_0 {
      color: #ff7d00;
    }
    &_1 {
      color: #00b42a;
    }
  }
  .item-content {
    display: flex;
    align-items: center;
  }
  .staff-line {
    margin: 0 5px;
  }
  .staffText {
    max-width: 86px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .fixed_width {
    min-width: 30px;
    display: inline-block;
  }
  .link {
    color: #1890ff;
  }

  .order-info-item + .order-info-item {
    margin-top: 4px;
  }
</style>
